# coding=utf-8
import datetime
import os
import sys
import time
import traceback

import pandas as pd
from loguru import logger

from cal_sh import get_sh_today_date
from mylib import update_all_csv
from send_email import send_email_plain


def run_sys(fw, cmd_str):
    current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    try:
        fw.write('{} start {}\n'.format(current_time, cmd_str))
        fw.flush()
        os.system(cmd_str)
        current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
        fw.write('{} finished {}\n'.format(current_time, cmd_str))
        fw.flush()
    except Exception as e:
        logger.error(e)
        send_email_plain.send_plain(f'{cmd_str} Exception {e} {traceback.format_exc()}\n')


def get_stock_today_date(param):
    df = pd.read_csv(f'stocks/{param}')
    today_date = df.iloc[0]['trade_date']
    return today_date


current_date = str(datetime.datetime.now().date()).replace('-', '')
log_path = 'log_{}.txt'.format(current_date)
send_email_plain.send_plain('计算开始')

with open(log_path, 'a') as fw:
    # 计算最近10日，价格相对于最近一次10日顶涨跌幅趋势
    run_sys(fw, 'python3 a_recent_d.py')
    # 获取底部涨幅大于3,反弹预测
    run_sys(fw, 'python3 gen_down_up2.py')
    # 计算跌幅大于20%
    run_sys(fw, 'python3 a_recent_low_up.py')
    # 分析今日跌幅大于20%支数
    run_sys(fw, 'python3 a_recent_low_up_ana.py')
    # # 获取低于谷底排名-个股跌幅前20名
    run_sys(fw, 'python3 gen_low_rank_old.py 1')

    # 计算行业距离顶底距离
    run_sys(fw, 'python3 a_recent_d_top_down.py')
    # 计算持仓股，下跌次数排序，累计跌幅排序，
    # run_sys(fw, 'python3 acc.py')
    # 计算行业 底部上涨/顶部下跌 次数排序
    # run_sys(fw, 'python3 aan.py 0 10 60')
    # run_sys(fw, 'python3 aatop_dis.py')
    # run_sys(fw, 'python3 aalow_dis.py')

    # 计算行业距离顶底距离
    run_sys(fw, 'python3 a_count1.py')

    # 最近一次顶点到低点距离最大（最近涨得最厉害的）
    # run_sys(fw, 'python3 a_top_down_dis_rank.py')

    # 计算底部反弹
    # run_sys(fw, 'python3 a_cal_one.py')

time.sleep(60 * 10)
send_email_plain.send_plain('计算完成')
